<?php
//不超时
    set_time_limit(0);
	ini_set("memory_limit","356M");
    /* 检查权限 */
    
    admin_priv('goods_export');
    $charset = empty($_POST['charset']) ? 'UTF8' : trim($_POST['charset']);
    include_once('includes/cls_phpzip.php');
    $zip = new PHPZip;

    $where = get_export_where_sql($_POST);
    
   
    
    /**只导出可同步更新到外网的产品**/
    if($_POST['is_sync']){
    	
    	$sql_to_export = "select group_concat(distinct log_key_id) from " . $ecs->table('goods_update_log') . "  where log_export_batch=0 order by log_id desc ";
    	$list_export_ids = $db->getOne($sql_to_export);
    	$list_export_ids = $list_export_ids?$list_export_ids:'-1';
    	$where .= "and g.goods_id in($list_export_ids)";
    }
    
    
    
    //add by darren 0623
   $count_sql =  "SELECT count(1) " .
           " FROM " . $ecs->table('goods') . " AS g LEFT JOIN " . $ecs->table('brand') . " AS b ON g.brand_id = b.brand_id " .
           " LEFT JOIN " . $ecs->table('suppliers') . " AS s  ON s.suppliers_id = g.suppliers_id  " .
           " LEFT JOIN " . $ecs->table('goods_type') . " AS d  ON d.cat_id = g.goods_type  " .
           "" . $where;
   $db_stat = $db->getOne($count_sql); 
   $perfile = 10000; 
   $for_stat  = ceil($db_stat/$perfile);   
   $for_stat  = $for_stat? $for_stat:1;
   $export_dir='../export/';  /*定义zip文件导出路径变量*/
   del_file($export_dir);	
   ob_end_clean();   
   print str_pad("",256);           
   echo "<p>export starting....<hr></p>";
   ob_flush();
   flush();
   
   for($i=0;$i<$for_stat;$i++):
    	echo 'creating file,from record '.($i*$perfile+1).'&nbsp;to&nbsp;'.($i+1)*$perfile.'......<br>';
	    ob_flush();
  		flush();	
	    $sql = "SELECT g.*, b.brand_name as brandname,s.suppliers_name as suppliers_name,d.cat_name as goods_type " .
	           " FROM " . $ecs->table('goods') . " AS g LEFT JOIN " . $ecs->table('brand') . " AS b ON g.brand_id = b.brand_id " .
	           " LEFT JOIN " . $ecs->table('suppliers') . " AS s  ON s.suppliers_id = g.suppliers_id  " .
	           " LEFT JOIN " . $ecs->table('goods_type') . " AS d  ON d.cat_id = g.goods_type  " .
	          
	           "" . $where.' limit '.intval($i*$perfile).','.$perfile.' ';
	           
	    $res = $db->query($sql);
	    /* csv文件数组 */
	    $goods_value = array();
	   	$goods_value['goods_name'] =  '';
		$goods_value['brand_name'] =  '';
		$goods_value['product_model'] = '';
		$goods_value['standard'] = '';		
		$goods_value['technical_parameters'] = '';
		$goods_value['main_material'] = '';
		$goods_value['shop_price'] = '';		
		$goods_value['cost'] =  '';
		$goods_value['unit'] =  '';
		$goods_value['categories_of_taxes'] = '';
		$goods_value['tax'] = '"' . $row['tax'] ;
		$goods_value['min_sale_qty'] = '';
		$goods_value['state_of_origin'] = '';
		$goods_value['production_cycle'] = '';
		$goods_value['goods_weight'] = '';
		$goods_value['gross_weight'] = '';
		$goods_value['package_size'] = '';
		$goods_value['product_certification'] = '';		
			
		/**二次调整**/
		$goods_value['attribute_230'] = '';
		$goods_value['attribute_231'] = '';
		$goods_value['attribute_232'] = '';
		$goods_value['attribute_233'] = '';
		$goods_value['attribute_234'] = '';
		$goods_value['attribute_235'] = '';
		$goods_value['attribute_236'] = '';
		$goods_value['attribute_238'] = '';
		$goods_value['attribute_237'] = '';
		
		
		$goods_value['goods_desc'] ='';
		$goods_value['goods_brief'] ='';
		
		
		
		/**二次调整**/
		$goods_value['attribute_224'] = '';
		$goods_value['attribute_226'] = '';
		$goods_value['attribute_227'] = '';
		$goods_value['attribute_228'] = '';
		$goods_value['attribute_229'] = '';
	
	
	
		
		$goods_value['cat_id'] = '';
		$goods_value['goods_sn'] = '';
		$goods_value['suppliers_name'] = '';
		$goods_value['hscode'] =  '';
		
		$goods_value['original_img'] = '';
		$goods_value['goods_img'] = '';
		$goods_value['goods_thumb'] = '';
		
		
	
		$goods_value['store'] = '';
		$goods_value['websites'] = '';
		$goods_value['status'] = '';
		$goods_value['tax_class_id'] = '';
		$goods_value['visibility'] = '';
		$goods_value['goods_number'] = '';
		$goods_value['is_on_sale'] =  '';
		$goods_value['type'] = '';
		$goods_value['attribute_set'] = '';
		$goods_value['pageurl'] = '';
		$goods_value['sort_order'] = '';
		if($charset=='UTF8'){
			array_walk($_LANG['magento'],create_function('&$n', '$n= mb_convert_encoding($n,  "CP936","UTF-8");;')); //编码转换
		}	 
		
	    $content = '"' . implode('","', $_LANG['magento']) . "\"\n";
		$csv_file = "../export/goods_list".$i.".csv";		
		$fp = fopen($csv_file,"w");
		$fput = null;
		foreach($_LANG['magento'] as $v) $fput[] = $v;
		fputcsv($fp,$fput);
		unset($fput,$goods_value);
	
	    while ($row = $db->fetchRow($res))
	    {
	 
	        
			//change      
			$goods_value['goods_name'] =  $row['goods_name'] ;
			$goods_value['brand_name'] =  $row['brandname'] ;
			$goods_value['product_model'] = $row['product_model'] ;
			$goods_value['standard'] = $row['standard'] ;
			
			$goods_value['technical_parameters'] = $row['technical_parameters'] ;
			$goods_value['main_material'] = $row['main_material'] ;
	
			
			$goods_value['shop_price'] = $row['shop_price'] ;
			
			$goods_value['cost'] =  $row['cost'] ;
			$goods_value['unit'] =  $row['unit'] ;
			$goods_value['categories_of_taxes'] = $row['categories_of_taxes'] ;
			$goods_value['tax'] = $row['tax'] ;
			$goods_value['min_sale_qty'] = $row['min_sale_qty'] ;
			$goods_value['state_of_origin'] = $row['state_of_origin'] ;
			$goods_value['production_cycle'] = $row['production_cycle'] ;
			$goods_value['goods_weight'] = $row['goods_weight'] ;
			$goods_value['gross_weight'] = $row['gross_weight'] ;
			$goods_value['package_size'] = $row['package_size'] ;
			$goods_value['product_certification'] = $row['product_certification'] ;
		 	$db_attributes = $db->getAll("select  attr_id,group_concat(attr_value) as attr_value from  " . $ecs->table('goods_attr') . " where goods_id='".$row['goods_id']."' group by goods_id,attr_id   ");
		 	foreach($db_attributes as $v){
		 		$attributes[$v['attr_id']] = $v['attr_value'] ;;
		 	}
		 	
		 	
			/**二次调整**/
			$goods_value['attribute_230'] = $attributes['230'];
			$goods_value['attribute_231'] = $attributes['231'];
			$goods_value['attribute_232'] = $attributes['232'];
			$goods_value['attribute_233'] = $attributes['233'];
			$goods_value['attribute_234'] = $attributes['234'];
			$goods_value['attribute_235'] = $attributes['235'];
			$goods_value['attribute_236'] = $attributes['236'];
			$goods_value['attribute_238'] = $attributes['238'];
			$goods_value['attribute_237'] = $attributes['237'];
			
			$goods_value['goods_desc'] = replace_special_char($row['goods_desc'], false) ;
			$goods_value['goods_brief'] = replace_special_char($row['goods_brief'], false) ;	
			
			
			
			/**二次调整**/
			$goods_value['attribute_224'] = $attributes['224'];
			$goods_value['attribute_226'] = $attributes['226'];
			$goods_value['attribute_227'] = $attributes['227'];
			$goods_value['attribute_228'] = $attributes['228'];
			$goods_value['attribute_229'] = $attributes['229'];
	
				
			
			$goods_value['cat_id'] = $row['cat_id'] ;
			$goods_value['goods_sn'] = $row['goods_sn'] ;
			$goods_value['suppliers_name'] = $row['suppliers_name'] ;
			$goods_value['hscode'] =  $row['hscode'] ;
			
			$goods_value['original_img'] = $row['original_img'] ;
			$goods_value['goods_img'] = $row['goods_img'] ;
			$goods_value['goods_thumb'] = $row['goods_thumb'] ;
			
			
			
			
			$goods_value['store'] = "en_us_ht";
			$goods_value['websites'] = $row['websites'] ;
			$goods_value['status'] =  $row['is_delete'] ? 'Dsiabled':'Enabled';
			$goods_value['tax_class_id'] = $row['tax_class_id'] ;
			$goods_value['visibility'] = $row['visibility'] ;
			$goods_value['goods_number'] = $row['goods_number'] ;
			$goods_value['is_on_sale'] =  $row['is_on_sale'] ;
			$goods_value['type'] = $row['type'] ;
			$goods_value['attribute_set'] = $row['goods_type'] ;
			$goods_value['pageurl'] = $row['pageurl'] ;
			$goods_value['sort_order'] = $row['sort_order'] ;
			
	        
	        if($charset=='UTF8'){
				array_walk($goods_value,create_function('&$n', '$n= mb_convert_encoding($n,  "CP936","UTF-8");')); //编码转换
			}
			
			$fput = null;
			foreach($goods_value as $v)	$fput[] = $v;			
			fputcsv($fp,$fput);	
			
	        // echo '开始抓取图片'.$row[goods_id].'...<br>';
	        //ob_flush();
  			//flush();
	        /* 压缩图片 */
	        if (!empty($row['goods_img']) && is_file(ROOT_PATH . $row['goods_img']))
	        {
	           // $zip->add_file(file_get_contents(ROOT_PATH . $row['goods_img']), $row['goods_img']);
			   $goods_img[] = $row['goods_img'];
	        }
	        if (!empty($row['original_img']) && is_file(ROOT_PATH . $row['original_img']))
	        {
	            //$zip->add_file(file_get_contents(ROOT_PATH . $row['original_img']), $row['original_img']);
				$original_img[] = $row['original_img'];
	        }
	        if (!empty($row['goods_thumb']) && is_file(ROOT_PATH . $row['goods_thumb']))
	        {
	           // $zip->add_file(file_get_contents(ROOT_PATH . $row['goods_thumb']), $row['goods_thumb']);
			   $goods_thumb[] = $row['goods_thumb'];
	        }
			unset($goods_value,$fput,$row,$db_attributes,$attributes);			
	    }
	    fclose($fp);
	    $charset = empty($_POST['charset']) ? 'UTF8' : trim($_POST['charset']);		  
		sleep(0);     
    endfor;
 	
	$goodszip=$export_dir."/goods.zip";		
	$zip->zip("../export",$goodszip); 
	/** deal with image **/
	/**
	echo 'deal image files...';
	ob_flush();
    flush();
	foreach($goods_thumb as $v) $zip->add_file(file_get_contents(ROOT_PATH . $v), $v);
	unset($goods_thumb);
	foreach($goods_img as $v) $zip->add_file(file_get_contents(ROOT_PATH . $v), $v);
	unset($goods_img);
	foreach($original_img as $v) $zip->add_file(file_get_contents(ROOT_PATH . $v), $v);
	unset($original_img);
	file_put_contents($goodszip,$zip->file());
	**/
	echo "<hr><p>zip file created successfully!</p>";
	echo "<p>Memory,used&nbsp",convert_memory(memory_get_usage(true)),"</p>";
    echo "<span><a href=\"".$goodszip."\">click here to download</a></span>";